<?php
/**
 * Created by 2019/4/13 0013
 * Effect: TokenValidationMiddleware.php
 * Author: 品花
 * Date: 2019/4/13 0013
 * Time: 上午 10:37
 */

namespace Middleware;


use Helper\Config;
use Helper\Output;

class SignValidationMiddleware
{
    protected static $instance;

    public static function getInstance()
    {
        if ( !isset(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    public function signAuth($request, $response)
    {

        if(true){
//            $request->post['sign'] = $this->getSign($request->post,$request->post['token']);
//            var_dump($request->post);
            var_dump($this->getSign($request->post,$request->post['token']));
        }

        $sign = $request->post['sign'];
        if (!$sign) {
            Output::responseJson(1008);
            return false;
        }

        //验证签名是否正确
        $params = $request->post;
        $token  = $params['token'];
        $res = $this->verifySign_($params, $token);
        if (!$res) {
            Output::responseJson(1009);
            return false;
        }


            return true;

    }


    /**
     * 验证签名
     * @param $data
     * @param $token
     * @return bool
     * @author 品花
     * @date 2019/4/25 0025 下午 4:16
     */
    function verifySign_($data,$token){

        $salt = Config::getInstance()->get('salt');

        $requestSign = $data['sign'];

        unset($data['sign']);
        unset($data['token']);

        ksort($data);

        $params = http_build_query($data);
//        var_dump(urldecode($params) . $token .$salt);
        $sign =  strtoupper(md5(md5(urldecode($params) . $token .$salt)));

        if($sign == $requestSign){
            return true;
        }else{
            return false;
        }
    }


    function getSign($data,$token){
        unset($data['token']);
        unset($data['sign']);
        $salt = Config::getInstance()->get('salt');
        ksort($data);

        $params = http_build_query($data);
//        var_dump(urldecode($params) . $token .$salt);
        $sign =  strtoupper(md5(md5(urldecode($params) . $token .$salt)));

        return $sign ;
    }
}

